package com.chixing.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayResponse;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.chixing.config.AlipayConfig;
import com.chixing.pojo.Customer;
import com.chixing.pojo.Flow;
import com.chixing.service.FlowService;
import com.chixing.service.MyOrderService;
import com.chixing.service.Orderreservice;
import com.chixing.util.ServerResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author dwe
 * @date 2021-11-03 19:25
 */
@Controller
@RequestMapping("ali")
public class AlipayController {
@Autowired
    private FlowService flowService;
    @Autowired
    private Orderreservice orderService;

    @PostMapping("pay")
    @ResponseBody
    public String pay(Integer orderId,Integer hotelId,String hotelName,String orderNumber,Float orderPrice ){
        System.out.println("支付中接收到的参数》》》》》》》》》》》》》》");
        System.out.println("orderId:" + orderId);
        System.out.println("hotelId:" + hotelId);
        System.out.println("hotelName:" + hotelName);
        System.out.println("orderNumber:" + orderNumber);
        System.out.println("orderPrice:" + orderPrice);

//(1)初始化AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id,
                AlipayConfig.merchant_private_key, "json", AlipayConfig.charset,
                AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        //(2)设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url); // 同步请求支付
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url); // 异步请求支付

//(3)支付请求中的订单信息 --- alirequest  context
        String out_trade_no = orderId.toString();
        String total_amount =  orderPrice.toString();
        String subject = hotelName;
        String body = "";
        String timeout_express = "1c";    // 该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）。 该参数数值不接受小数点， 如 1.5h，可转换为 90m。

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"timeout_express\":\""+ timeout_express +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");


        String payResult = null;
        try {
            AlipayResponse alipayResponse =  alipayClient.pageExecute(alipayRequest);

            System.out.println("pay code:"+ alipayResponse.getCode());
            System.out.println("pay getSubCode:"+ alipayResponse.getSubCode());
            System.out.println("pay getMsg:"+ alipayResponse.getMsg());
            System.out.println("pay isSuccess:"+ alipayResponse.isSuccess());
            payResult =  alipayResponse.getBody();// getBody() 支付后，支付宝返回的支付的信息
            System.out.println("支付宝返回的支付的信息：" + payResult);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        return payResult;
    }


    // 支付后的 获得 支付宝的信息 payResult --->request
    @GetMapping("alipayNotifyNotice")
    public ModelAndView notifyNotice (HttpServletRequest request, HttpServletResponse response){
        System.out.println("同步返回页面操作。。。。。");
        ModelAndView mav = new ModelAndView("alipaySuccess");
        Map<String,String[]> map= request.getParameterMap();
        System.out.println(">>>>>支付后的 获得 支付宝的信息 " + map);
        return mav;
    }
    @RequestMapping("alipayReturnNotice")
    public ModelAndView returnNotice  (HttpServletRequest request,HttpServletResponse response){
        System.out.println("异步返回页面操作。。。。。");



        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            System.out.println("return notice name:"+name);
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            try {
                valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            System.out.println("支付后的 获得 支付宝的信息 " + name + "," +valueStr );
            params.put(name, valueStr);
        }
        System.out.println("params:"+params);


        String out_trade_no = null;
        String trade_no = null;
        String orderPrice =null;
        try {
            out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
            //支付宝交易号
            trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
            //付款金额
            orderPrice =new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");


        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        Integer orderId = Integer.valueOf(out_trade_no);
        // 添加流水
        Flow flow = new Flow();
       Customer customer = (Customer) request.getSession().getAttribute("loginCustomer");
        System.out.println("当前登录的用户：" + customer);
        flow.setCusId(customer.getCusId());
        flow.setFlowDate(new Date());
        flow.setFlowNumber(Math.abs((int)(new Date().getTime())));
        flow.setFlowPrice(Float.valueOf(orderPrice));
         flow.setOrdId(orderId);
        flowService.save(flow);
        //修改订单状态
        orderService.updateOrderStatus(orderId,1); // 0： 未支付 ， 1： 表示 已支付
        // 查询刚支付的流水信息
        ServerResponse serverResponse = flowService.getByOrderId(orderId);
        ModelAndView mav = new ModelAndView("alipaySuccess");
        mav.addObject("serverResponse",serverResponse);
        return  mav;
    }
}



